﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Security.Cryptography;
using System.Text;
using System.Web.Script.Serialization;
using System.Xml.Serialization;

namespace TOOLS
{
   public static class Common
    {
        #region 反序列化
        /// <summary>
            /// 反序列化
            /// </summary>
            /// <param name="type">类型</param>
            /// <param name="xml">XML字符串</param>
            /// <returns></returns>
        public static T XMLDeserialize<T>(this string xml)
        {
            try
            {
                using (StringReader sr = new StringReader(xml))
                {
                    XmlSerializer xmldes = new XmlSerializer(typeof(T));
                    return (T)xmldes.Deserialize(sr);
                }
            }
            catch (Exception e)
            {

                return default(T);
            }
        }
      
        #endregion

        #region 序列化
        /// <summary>
            /// 序列化
            /// </summary>
            /// <param name="type">类型</param>
            /// <param name="obj">对象</param>
            /// <returns></returns>
        public static string XMLSerializer(this object obj)
        {
            MemoryStream Stream = new MemoryStream();
            XmlSerializer xml = new XmlSerializer((obj).GetType());
            try
            {
                //序列化对象
                xml.Serialize(Stream, obj);
            }
            catch (InvalidOperationException)
            {
                throw;
            }
            Stream.Position = 0;
            StreamReader sr = new StreamReader(Stream);
            string str = sr.ReadToEnd();

            sr.Dispose();
            Stream.Dispose();

            return str;
        }

        #endregion
        public static string ToJSON(this object obj)
        {
            return JsonConvert.SerializeObject(obj, Formatting.Indented, new JsonSerializerSettings
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            });
        }
        public static T JsonToObj<T>(this string data)
        {
            return JsonConvert.DeserializeObject<T>(data, new JsonSerializerSettings
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            });
        }
        public static int ToInt(this string t)
        {
            int r;
            int.TryParse(t, out r);//这里当转换失败时返回的id为0
            return r;
        }
        public static float ToFloat(this string t)
        {
            float r;
            float.TryParse(t, out r);//这里当转换失败时返回的id为0
            return r;
        }
        #region Dictionnary
        static string mSplit = "-||||-";
        static string rSplit = "-::::-";
        public static string[] Split(this string s,string splitString)
        {

            return s.Split(new string[] { splitString }, StringSplitOptions.None);
        }
        public static Dictionary<string, string> StringToDictionary(this string s)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            string[] items = s.Split(new string[] { mSplit }, StringSplitOptions.None);

            foreach (string item in items)
            {
                if (item == "")
                {
                    continue;
                }
                string[] temp = item.Split(new string[] { rSplit }, StringSplitOptions.None);
                result.Add(temp[0], temp[1]);
            }
            return result;
        }
        public static Dictionary<string, string> StringToDictionary(this string s,string mSplit,string rSpilt)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            string[] items = s.Split(new string[] { mSplit }, StringSplitOptions.None);

            foreach (string item in items)
            {
                if (item == "")
                {
                    continue;
                }
                string[] temp = item.Split(new string[] { rSpilt }, StringSplitOptions.None);
                result.Add(temp[0], temp[1]);
            }
            return result;
        }
        public static string DictionaryToString(this Dictionary<string, string> d)
        {
            StringBuilder temp = new StringBuilder();
            foreach (var item in d)
            {
                temp.Append(item.Key + rSplit + item.Value);
                if (d.Count != 0)
                {
                    temp.Append(mSplit);
                }
            }
            return temp.ToString();
        }
        #endregion
        public static string GetMD5(this string myString)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] fromData = System.Text.Encoding.Unicode.GetBytes(myString);
            byte[] targetData = md5.ComputeHash(fromData);
            string byte2String = null;

            for (int i = 0; i < targetData.Length; i++)
            {
                byte2String += targetData[i].ToString("x");
            }

            return byte2String;
        }
        public static string GetRandomString(this string allChar, int codeCount)
        {
            if (allChar.Length == 0)
            {
                allChar = "1,2,3,4,5,6,7,8,9,0,A,B,C,D,E,F,G,H,i,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,~,!,@,#,$,%,^,&,*,(,),_,+,-,=";
            }
            string[] allCharArray = allChar.Split(',');
            string RandomCode = "";
            int temp = -1;
            Random rand = new Random();
            for (int i = 0; i < codeCount; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(temp * i * ((int)DateTime.Now.Ticks));
                }

                int t = rand.Next(allCharArray.Length - 1);

                while (temp == t)
                {
                    t = rand.Next(allCharArray.Length - 1);
                }

                temp = t;
                RandomCode += allCharArray[t];
            }
            return RandomCode;
        }
     
    }
}
